package com.solution.admin.auth.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.solution.admin.auth.constants.AuthConstants;
import com.solution.admin.auth.entity.OrgEntity;
import com.solution.admin.auth.entity.UserEntity;
import com.solution.admin.auth.service.OrgService;
import com.solution.admin.auth.service.UserService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.IS_DELETE;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.controller.BaseController;

/**
 * 组织信息管理层
 * 
 * @author diwankang
 * @version 2017年4月6日
 */
@RequestMapping("/org")
@Controller
public class OrgController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(OrgController.class);

	@Autowired
	private OrgService orgService;

	@Autowired
	private UserService userService;

	/**
	 * 跳转组织信息页面
	 * @return
	 * @author diwankang
	 * @date 2017年4月12日 下午3:32:35
	 * @modify <scy> <2017年4月12日 下午3:32:35>
	 */
	@RequestMapping("/toOrgPage")
	public ModelAndView toOrgPage(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView();

		modelAndView.setViewName("auth/org/org_list");
		return modelAndView;
	}
	
	/**
	 * 跳转组织架构选择器页面
	 * @param request
	 * @return
	 * @author james
	 */
	@RequestMapping("/toOrgSelector")
	public String toOrgSelector(HttpServletRequest request) {
		return "auth/org_selector";
	}
	
	/**
	 * 查询组织架构信息(for selector )
	 * @return
	 * @author james
	 */
	@RequestMapping("/listOrgForSelector")
	@ResponseBody
	public List<OrgEntity> listOrgForSelector(HttpServletRequest request) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("parentId", request.getParameter("parentId"));
		List<OrgEntity> orgList = orgService.listOrg(param);
		return orgList;
	}

	/**
	 * 查询org信息
	 * 
	 * @return
	 * @author diwankang
	 * @date 2017年4月12日 下午4:43:06
	 * @modify <scy> <2017年4月12日 下午4:43:06>
	 */
	@RequestMapping("/listOrg")
	@ResponseBody
	public Map<String, Object> listOrg() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<OrgEntity> treeList = orgService.listOrgByDealerId();
			resultMap.put("treeList", treeList);
		} catch (Exception e) {
			logger.error("系统异常===", e);
			e.printStackTrace();
		}
		return resultMap;
	}
	
	@RequestMapping("/orgTree")
	@ResponseBody
	public JSONArray orgTree(){
		List<OrgEntity> treeList = orgService.listOrgByDealerId();
		JSONArray rows =new JSONArray();
		for (int i = 0; i < treeList.size(); i++) {
			JSONObject json = new JSONObject();
			json.put("id", treeList.get(i).getId());
			json.put("pid", treeList.get(i).getParentId());
			json.put("name", treeList.get(i).getOrgName());
			rows.add(json);
		}
		return rows;
	}
	/**
	 * 跳转到添加岗位页面
	 * @param request
	 * @return
	 * @author qiaoenyin
	 * @date 2017年4月26日 下午3:16:26
	 */
	@RequestMapping("/toAddOrg")
	public String toAddPosition(HttpServletRequest request) {
		// 新增操作
		int parentId=Integer.parseInt(request.getParameter("parentId"));
		request.setAttribute("parentId",parentId);
		return "auth/org/org_form";
	}

	/**
	 * 新增组织
	 * 
	 * @param orgEntity
	 * @return
	 * @exception/throws [异常类型][异常说明]
	 * @author diwankang
	 * @date 2017年4月13日 下午2:03:54
	 * @modify <scy> <2017年4月13日 下午2:03:54>
	 */
	@RequestMapping("/addOrg")
	@ResponseBody
	public Map<String, Object> addOrg(HttpServletRequest request, OrgEntity orgEntity) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			/**
			String orgName = request.getParameter("orgName");
			Integer status = Integer.parseInt(request.getParameter("status"));
			String deptHead = request.getParameter("deptHead");
			String deptLeader = request.getParameter("deptLeader");
			String deptAdministrator = request.getParameter("deptAdministrator");
			orgEntity.setOrgName(orgName);
			orgEntity.setStatus(status);
			orgEntity.setOrgCode("ORG_" + orgEntity.getId().toString());
			*/
			orgEntity.setStatus(STATUS.ENABLED.getId());
			orgEntity.setIsDelete(AuthConstants.IS_DELETE.NOT_DELETE.getId());
			orgEntity.setCreater(getUserCode());
			Long res = orgService.saveOrgInfo(orgEntity);
			if (res != null) {
				result.put("code", AuthConstants.ADD_RESULT.SUCCESS.getCode());
				result.put("msg", AuthConstants.ADD_RESULT.SUCCESS.getMsg());
				return result;
			} else {
				result.put("code", AuthConstants.ADD_RESULT.FAILED.getCode());
				result.put("msg", AuthConstants.ADD_RESULT.FAILED.getMsg());
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", AuthConstants.ADD_RESULT.FAILED.getCode());
			result.put("msg", AuthConstants.ADD_RESULT.FAILED.getMsg());
			return result;
		}
	}

	/**
	 * 修改用户信息
	 * 
	 * @author: solin
	 * @date: 2017年4月21日 下午5:22:00
	 * @param orgEntity
	 * @return
	 */
	@RequestMapping("/updateOrg")
	@ResponseBody
	public Map<String, Object> updateOrg(HttpServletRequest request, OrgEntity org) {
		/**
		String msg = "修改失败 ";
		Long id = Long.parseLong(request.getParameter("id"));
		Long parentId = Long.parseLong(request.getParameter("parentId"));
		Integer status = Integer.parseInt(request.getParameter("status"));
		String orgName = request.getParameter("orgName");
		String deptHead = request.getParameter("deptHead");
		String deptLeader = request.getParameter("deptLeader");
		String deptAdministrator = request.getParameter("deptAdministrator");
		*/
		int count = orgService.updateOrg(org);
		HashMap<String, Object> result = new HashMap<String, Object>();
		if (count > 0) {
			result.put("code", AuthConstants.EDIT_RESULT.SUCCESS.getCode());
			result.put("msg", AuthConstants.EDIT_RESULT.SUCCESS.getMsg());
			return result;
		} else {
			result.put("code", AuthConstants.EDIT_RESULT.FAILED.getCode());
			result.put("msg", AuthConstants.EDIT_RESULT.FAILED.getMsg());
			return result;
		}
	}
	/**
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年9月14日 上午8:59:34
	 */
	@RequestMapping("/delOrg")
	@ResponseBody
	public Map<String, Object> delOrg(HttpServletRequest request, Long id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		String msg = "";
		try {
			if (null == id) {
				resultMap.put(PublicStatus.RESULT_CODE, 0);
				resultMap.put(PublicStatus.RESULT_MSG, "删除部门失败，请重试！");
				return resultMap;
			}
			// 判断是否还有子分类（没删除的）
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("parentId", id);
			param.put("isDelete", IS_DELETE.NORMAL.getId());
			List<OrgEntity> orgList = orgService.listOrg(param);
			if (orgList != null && orgList.size() > 0) {
				result = 0;
				msg = "此部门下面有子部门，禁止删除！";
			} else {
				// 没有子部门了，那就看看当前部门下还有没有员工
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("orgId", id);
				List<UserEntity> userList = userService.getUserList(paramMap);
				if(null != userList && userList.size() > 0) {
					result = 0;
					msg = "此部门已关联了人员，无法删除！";
				} else {
					OrgEntity org = new OrgEntity();
					org.setId(id);
					org.setModifier(getUserCode());
					org.setIsDelete(IS_DELETE.DELETED.getId());
					int rows = orgService.updateOrg(org);
					if (rows > 0) {
						result = 1;
						msg = "删除成功!";
					} else {
						result = 0;
						msg = "删除失败!";
					}
				}
			}
			resultMap.put(PublicStatus.RESULT_CODE, result);
			resultMap.put(PublicStatus.RESULT_MSG, msg);
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, -1);
			resultMap.put(PublicStatus.RESULT_MSG, "删除部门异常，请重试！");
			e.printStackTrace();
		}
		return resultMap;
	}
}
